<template>
  <div class="cart-wrapper">
    <h1>总价：{{ totalPrice }}</h1>
    <ul v-for="item in cartList" :key="item.id">
      <li><img :src="item.img" alt="" /></li>
      <li>{{ item.goodsName }}</li>
      <li>
        <span class="base-btn" @click="handleAddItem(item)">+</span>
        <span class="base-btn">{{ item.count }}</span>
        <span class="base-btn" @click="handleReduceItem(item)">-</span>
      </li>
    </ul>
  </div>
</template>
<script lang="ts">
import { defineComponent, computed, watch, watchEffect } from 'vue'
import { useStore } from 'vuex'
import { CartItemType } from '../store'

export default defineComponent({
  setup() {
    // 使用vuex仓库
    // 拿取store数据，要配合计算属性
    const store = useStore()
    const handleAddItem = (item: CartItemType) => {
      store.commit('SET_ADD_ITEM', item)
    }

    // 从vuex中拿到总价
    const totalPrice = computed(() => store.getters.totalPrice)
    // 拿渲染数据
    const cartList = computed(() => store.state.cartList)

    watchEffect(() => {
      console.log('cartList:', cartList)
    })

    const handleReduceItem = (item: CartItemType) => {
      store.commit('SET_REDUCE_ITEM', item)
    }

    // console.log(store.state)
    // console.log(cartList, 'cartList')
    return {
      cartList,
      totalPrice, // 总价
      handleAddItem,
      handleReduceItem
    }
  }
})
</script>
<style lang="scss">
.base-btn {
  border-radius: 5px;
  cursor: pointer;
  width: 35px;
  height: 35px;
  font-size: 25px;
  text-align: center;
  line-height: 35px;
  padding: 5px;
  margin: 5px;
  background: lightcoral;
  color: white;
  display: inline-block;
}
</style>
